<template>
  <Component
    :is="drawer ? 'k-drawer' : 'k-dialog'"
    v-if="visible"
    v-model="visible"
    :title="title"
    :width="width"
    v-bind="$attrs"
    :loading="loading"
    :content-loading="contentLoading"
    class="is-form"
    @submit="onSubmit"
    @cancel="onCancel"
  >
    <template #title="slotProps">
      <slot name="title" v-bind="slotProps"></slot>
    </template>
    <k-form
      v-if="visible"
      ref="formRef"
      :inline="inline"
      :label-width="labelWidth"
      :model="model"
      :rules="rules"
      v-bind="$attrs"
    >
      <slot></slot>
    </k-form>
  </Component>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import KForm from './k-form.vue';
defineOptions({
  name: 'KFormModel',
  inheritAttrs: false
});

interface Props {
  modelValue?: boolean;
  title?: string;
  width?: string;
  model?: any;
  rules?: any;
  labelWidth?: string;
  inline?: boolean;
  loading?: boolean;
  contentLoading?: boolean;
  drawer?: boolean;
  modalSize?: string;
}
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  title: '',
  width: undefined,
  model: () => ({}),
  rules: () => ({}),
  labelWidth: '72px',
  inline: false,
  loading: false,
  contentLoading: false,
  drawer: false,
  modalSize: ''
});
const emits = defineEmits(['submit', 'cancel', 'update:model-value']);
const visible = computed({
  get: () => {
    return props.modelValue;
  },
  set: (val: boolean) => {
    emits('update:model-value', val);
  }
});

const formRef = ref();
const onSubmit = async () => {
  await formRef.value.validate();
  emits('submit', props.model);
};
const onCancel = () => {
  resetFields();
  clearValidate();
  visible.value = false;
};
const validate = async () => {
  if (formRef?.value?.validate) {
    await formRef.value.validate();
  }
};
const resetFields = () => {
  if (formRef?.value?.resetFields) {
    formRef.value.resetFields();
  }
};
const reset = resetFields;
const clearValidate = () => {
  if (formRef?.value?.clearValidate) {
    formRef.value.clearValidate();
  }
};
const validateField = async (field: string) => {
  if (formRef?.value?.validateField) {
    await formRef.value.validateField(field);
  }
};
defineExpose({
  formRef,
  validate,
  reset,
  resetFields,
  clearValidate,
  validateField
});
</script>
